package com.simplenix.nicasio.tags;

import com.simplenix.nicasio.hmaint.EntityDefinition;
import com.simplenix.nicasio.hmaint.EntityFactory;
import com.simplenix.nicasio.hmaint.HMaintException;
import com.simplenix.nicasio.hmaint.servlet.HMaintService;
import com.simplenix.nicasio.hmaint.util.HMaintUtil;
import com.simplenix.nicasio.misc.AppException;
import com.simplenix.nicasio.misc.Internationalization;
import com.simplenix.nicasio.misc.StrUtil;
import com.simplenix.nicasio.persistence.HibernateUtil;
import com.simplenix.nicasio.sys.SystemDef;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import org.hibernate.Criteria;

/**
 *
 * @author fronald
 */
public class Maint extends SimpleTagSupport {

	private java.lang.String entityBean;

	@Override
	public void doTag() throws JspException {
		JspWriter out = getJspContext().getOut();
		PageContext pc = (PageContext) this.getJspContext();
		try {
			//Render the list
			java.lang.String html = "";
			html += "<table id='table_" + this.entityBean.replaceAll("\\.", "_") + "'></table>\n";
			EntityDefinition entityDef = EntityFactory.getInstance().getEntityDefinition(this.entityBean);
			html += "<script>";
			html += "$(\"#table_" + this.entityBean.replaceAll("\\.", "_") + "\").flexigrid({ \n";
			html += "url: '" + SystemDef.getInstance().getContextPath() + "/hmaint?ACTION=JSONDATA&ENTITY=" + this.entityBean + "',\n";
			html += "dataType: 'json',\n";
			html += "colModel : [\n";
			for (java.lang.String field : entityDef.getFieldsNames()) {
				if (!entityDef.getFieldsHiddenOnList().contains(field)) {
					html += "{display: '" + Internationalization.getInstance().getString(this.entityBean + "." + field) + "', name : '" + field + "',width: " + entityDef.getFieldLength(field) + ", sortable : true, align: '" + (entityDef.getFieldType(field).equals(EntityDefinition.TYPE_NUMBER) || entityDef.getFieldType(field).equals(EntityDefinition.TYPE_LONG) ? "right" : "left") + "'},";
				}
			}
			html = html.substring(0, html.length() - 1);
			html += "],\n";
			html += "buttons : [\n";
			html += " {name: '" + Internationalization.getInstance().getString("add") + "', onpress : handleGridActions" + this.entityBean.replaceAll("\\.", "_") + "},\n";
			html += " {name: '" + Internationalization.getInstance().getString("delete") + "', onpress : handleGridActions" + this.entityBean.replaceAll("\\.", "_") + "},\n";
			html += " {name: '" + Internationalization.getInstance().getString("update") + "', onpress : handleGridActions" + this.entityBean.replaceAll("\\.", "_") + "},\n";
			html += " {separator: true}";
			html += "],\n";
			if (entityDef.getSearchableFields().size() > 0) {
				html += "searchitems : [\n";
				for (java.lang.String s : entityDef.getSearchableFields()) {
					html += "{display: '" + Internationalization.getInstance().getString(this.entityBean + "." + s) + "', name : '" + s + "'},";
				}
				html = html.substring(0, html.length() - 1);
				html += "],\n";
			}
			html += "usepager: true, \n";
			html += "singleSelect: true, \n";
			html += "onRowSelected: RowSelected" + this.entityBean.replaceAll("\\.", "_") + ", \n";
			html += "title: '" + Internationalization.getInstance().getString(this.entityBean) + "s',\n";
			html += "useRp: true,\n";
			if (!StrUtil.nvl(entityDef.getDescriptionField()).equals("")) {
				html += "sortname: '" + entityDef.getDescriptionField() + "',\n";
				html += "sortorder: 'asc',\n";
			}
			html += "rp: 15,\n";
			html += "showTableToggleBtn: true,\n";
			html += "height: 'auto'\n";
			html += "}\n";
			html += ");\n";
			html += "function handleGridActions" + this.entityBean.replaceAll("\\.", "_") + "(com,grid){\n";
			html += "   if(com == '" + Internationalization.getInstance().getString("add") + "'){ \n";
			html += "      $(':submit').removeAttr('disabled'); \n";
			html += "      $('#add" + this.entityBean.replaceAll("\\.", "_") + "').dialog('open');\n";
			html += "   } else if (com == '" + Internationalization.getInstance().getString("delete") + "') { \n";
			html += "		if(selected" + this.entityBean.replaceAll("\\.", "_") + " != null && confirm('" + Internationalization.getInstance().getString("areyousure") + "')){ \n";
			html += "          document.location.href='" + SystemDef.getInstance().getContextPath() + "/hmaint?ENTITY=" + this.entityBean + "&ACTION=" + HMaintService.ACTION_DELETE + "&" + HMaintService.PARAM_BACK_TO + "=" + ((HttpServletRequest) pc.getRequest()).getRequestURI().replaceAll("\\.jsp", ".htm").replaceAll("/", "%2F") + "&" + entityDef.getKeyFieldName() + "='+selected" + this.entityBean.replaceAll("\\.", "_") + "; \n";
			html += "       }\n;";
			html += "   } else if (com == '" + Internationalization.getInstance().getString("update") + "' && selected" + this.entityBean.replaceAll("\\.", "_") + " != null) { \n";
			html += "      $.get('" + SystemDef.getInstance().getContextPath() + "/hmaint?ENTITY=" + this.entityBean + "&ACTION=" + HMaintService.ACTION_VIEWUPDATE + "&" + HMaintService.PARAM_BACK_TO + "=" + ((HttpServletRequest) pc.getRequest()).getRequestURI().replaceAll("\\.jsp", ".htm").replaceAll("/", "%2F") + "&" + entityDef.getKeyFieldName() + "='+selected" + this.entityBean.replaceAll("\\.", "_") + ", function(data){$('#update" + this.entityBean.replaceAll("\\.", "_") + "').html(data)});";
			html += "      $('#update" + this.entityBean.replaceAll("\\.", "_") + "').dialog('open');\n";
			html += "   }\n";
			html += "}\n";
			int height = entityDef.getFieldsNames().size() * 30 + 40;
			html += "$(document).ready(function(){$('#add" + this.entityBean.replaceAll("\\.", "_") + "').dialog({ autoOpen: false, height: " + height + ", width: 450, title: '" + Internationalization.getInstance().getString("add") + " " + Internationalization.getInstance().getString(this.entityBean) + "' })});\n";
			html += "$(document).ready(function(){$('#update" + this.entityBean.replaceAll("\\.", "_") + "').dialog({ autoOpen: false, height: " + height + ", width: 450, title: '" + Internationalization.getInstance().getString("update") + " " + Internationalization.getInstance().getString(this.entityBean) + "' })});\n";
			html += "var selected" + this.entityBean.replaceAll("\\.", "_") + "; \n";
			html += "function RowSelected" + this.entityBean.replaceAll("\\.", "_") + "(id,row,grid){\n";
			html += "	selected" + this.entityBean.replaceAll("\\.", "_") + " = id;\n";
			html += "} \n";
			html += "</script>\n";
			html += this.getAddDialog(entityDef);
			html += "<div id='update" + this.entityBean.replaceAll("\\.", "_") + "'></div>";
			out.write(html);
			if (entityDef == null) {
				throw new JspException("No valid entity bean");
			}
		} catch (Exception ex) {
			throw new JspException("Error in Maint tag", ex);
		}
	}

	private java.lang.String getAddDialog(EntityDefinition ed) throws AppException {
		java.lang.String rtn = "";
		rtn += "<div id='add" + this.entityBean.replaceAll("\\.", "_") + "'>\n";
		PageContext pc = (PageContext) this.getJspContext();
		java.lang.String backTo = ((HttpServletRequest) pc.getRequest()).getRequestURI().replaceAll("\\.jsp", ".htm");
		rtn += surroundWithForm(ed.getCustomAdd().getHtml(ed, rtn), ed, backTo);
		rtn += "</div>";
		return rtn;
	}

	public static java.lang.String loadForm(EntityDefinition ed, java.lang.String id) throws HMaintException, AppException {
		java.lang.String rtn = "";
		Object o = null;
		if (!StrUtil.nvl(id).equals("")) {
			rtn += "<input type='hidden' name='" + ed.getKeyFieldName() + "' value='" + id + "'></input>";
			o = HMaintUtil.findById(ed.getEntityClass(), id);
		}
		rtn += "<table>";
		for (java.lang.String field : ed.getFieldsNames()) {
			if (!ed.getFieldsHiddenOnAdd().contains(field)) {
				rtn += "<tr><td>" + Internationalization.getInstance().getString(ed.getEntityClass().getName() + "." + field) + "</td><td>";
				if (ed.getFieldType(field).equals(EntityDefinition.TYPE_STRING)) {
					if (ed.getSecretFields().contains(field)) {
						rtn += "<input type='password' maxlenght='" + ed.getFieldLength(field) + "' size='50' name='" + field + "' value='" + getValue(o, field) + "'></input>";
					} else {
						rtn += "<input type='text' maxlenght='" + ed.getFieldLength(field) + "' size='50' name='" + field + "' value='" + getValue(o, field) + "'></input>";
					}
				} else if (ed.getFieldType(field).equals(EntityDefinition.TYPE_TEXT)) {
					rtn += "<textarea name='" + field + "' value='" + getValue(o, field) + "'></textarea>";
				} else if (ed.getFieldType(field).equals(EntityDefinition.TYPE_NUMBER)) {
					rtn += "<input type='text' name='" + field + "' value='" + getValue(o, field) + "'></input>";
				} else if (ed.getFieldType(field).equals(EntityDefinition.TYPE_LONG)) {
					rtn += "<input type='text' name='" + field + "' value='" + getValue(o, field) + "'></input>";
				} else if (ed.getFieldType(field).equals(EntityDefinition.TYPE_BOOLEAN)) {
					java.lang.String nSelected = !getValue(o, field).equals("Y") ? "selected" : "";
					java.lang.String ySelected = getValue(o, field).equals("Y") ? "selected" : "";
					rtn += "<input type='radio' name='" + field + "' value='N' " + nSelected + ">" + Internationalization.getInstance().getString("not") + "</input><input type='radio' name='" + field + "' value='Y' " + ySelected + ">" + Internationalization.getInstance().getString("yes") + "</input>";
				} else if (ed.getFieldType(field).equals(EntityDefinition.TYPE_DATE)) {
					rtn += "<input type='text' name='" + field + "' value='" + getValue(o, field) + "'></input>";
				} else if (ed.getFieldType(field).equals(EntityDefinition.TYPE_DATE_TIME)) {
					rtn += "<input type='text' name='" + field + "' value='" + getValue(o, field) + "'></input>";
				}
				rtn += "</td></tr>";
			}
		}
		rtn += "</table>";
		return rtn;
	}

	public static java.lang.String surroundWithForm(java.lang.String html, EntityDefinition ed, java.lang.String backTo) throws HMaintException, AppException {
		java.lang.String rtn = "<form method='POST' action='" + SystemDef.getInstance().getContextPath() + "/hmaint?ENTITY=" + ed.getEntityClass().getName() + "&ACTION=" + HMaintService.ACTION_ADDUPDATE + "'>\n" + html + "\n";
		rtn += "<input type='hidden' name='" + HMaintService.PARAM_BACK_TO + "' value='" + backTo + "'></input>";
		if (ed.getFieldsNames().size() > 0) {
			rtn += "<center><input type='submit' name='subButton' value='" + Internationalization.getInstance().getString("save") + "'></input></center>";
		}
		return rtn + "</form>";
	}

	private static java.lang.String getValue(Object o, java.lang.String field) throws HMaintException {
		if (o == null) {
			return "";
		} else {
			return HMaintUtil.getValue(o, field);
		}
	}

	public void setEntityBean(java.lang.String entityBean) {
		this.entityBean = entityBean;
	}

}
